package com.micro.turtle.runner;

import cn.hutool.core.collection.CollectionUtil;
import com.micro.turtle.constant.Cmd;
import com.micro.turtle.model.Project;
import com.micro.turtle.model.resp.PipelineResp;
import com.micro.turtle.util.Log;
import java.util.Collections;
import java.util.List;

/**
 * 批量脚本
 *
 * @author jason.lv
 * @since 2022/1/24 14:50
 */
public class BatchRunner extends Runner {

    public BatchRunner() {
        super(Cmd.PIPE_BATCH);
    }

    @Override
    void exec() {
        // 拉取项目组下的项目列表
        String next = scannerNext("输入项目组ID:");
        List<Project> projects = ProjectRunner.list(Integer.valueOf(next));
        ProjectRunner.print(projects);

        // Step1: 是否指定项目
        List<Project> list = stepOne();
        if (CollectionUtil.isNotEmpty(list)) {
            projects = list;
        }

        // Step2: 生成项目
        stepTwo(projects);
    }

    private List<Project> stepOne() {
        Log.line(20);
        String next = scannerNext("是否指定项目: y/n");
        switch (next) {
            case "y":
                next = scannerNext("输入项目ID:");
                return Collections.singletonList(ProjectRunner.detail(Integer.valueOf(next)));
            case "n":
                Log.line(20);
                break;
            default:
                Log.info("无效的指令...");
                Log.line(20);
                break;
        }
        return null;
    }

    private void stepTwo(List<Project> projects) {
        Log.line(20);
        String next = scannerNext("以上项目是否全部创建: y/n");
        switch (next) {
            case "y":
                bacthCreate(projects);
                break;
            case "n":
                Log.line(20);
                break;
            default:
                Log.info("无效的指令...");
                Log.line(20);
                break;
        }
    }

    private void bacthCreate(List<Project> projects) {
        if (CollectionUtil.isNotEmpty(projects)) {
            for (Project project : projects) {
                Log.info("Pipeline Creating >>>>> 项目ID: %s >> %s", project.getId(), project.getName());
                PipelineResp pipeline = PipelineRunner.create(project.getId());
                Log.info("Pipeline Created >>>>> Id:%s ||| %s ||| %s", pipeline.getId(), pipeline.getStatus(), pipeline.getRef());
                Log.line(20);
            }
        }
    }
}
